package com.fudan.adse.domain.dto;

import com.fudan.adse.domain.bo.UserBO;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;

/**
 * @author Jerry Zhang <zhangjian16@fudan.edu.cn>
 * @desc Spring Security需要的用户详情
 * @date 2022-09-14 12:14
 */
@Data
@EqualsAndHashCode
public class AdminUserDetails implements UserDetails {
    private String username;
    private String password;
    private Boolean status;

    private String client;
    private Collection<SimpleGrantedAuthority> authorities;


    public AdminUserDetails(UserBO user) {
        this.username = user.getUsername();
        this.password = user.getPassword();
        this.status = user.getStatus();
        if (user.getRoles() != null && !user.getRoles().isEmpty()) {
            this.authorities = new ArrayList<>();
            user.getRoles().forEach(role -> this.authorities.add(new SimpleGrantedAuthority(role)));
        }
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.authorities;
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return this.status;
    }
}
